
package com.xkw.autocode.web.system.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Producer;
import com.xkw.autocode.base.BaseController;
import com.xkw.autocode.logaspect.SysLog;
import com.xkw.autocode.util.IpUtils;
import com.xkw.autocode.util.MD5;
import com.xkw.autocode.vo.UserConfigVo;
import com.xkw.autocode.web.common.Result;
import com.xkw.autocode.web.system.SystemUrlUtil;
import com.xkw.autocode.web.userconfig.ao.UserConfigAo;

/**
 * 登录相关
 */
@Controller
public class LoginController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private UserConfigAo userConfigAo;

	@Autowired
	private Producer producer;
	
	/**
	 * 图片验证码
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = SystemUrlUtil.LOGIN_CODE)
	public void captcha(HttpServletRequest request,HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        
        //保存到shiro session
        super.setSessionLoginCode(request, text);
        
        ServletOutputStream out = response.getOutputStream();
        
        ImageIO.write(image, "jpg", out);
	}
	
	/**
	 * 登录
	 */
	@SysLog(option="登录",value="用户登录")
	@ResponseBody
	@PostMapping(value = SystemUrlUtil.DO_LOGIN)
	public Result login(HttpServletRequest request, String username, String pwdvalue, String captcha) {

		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(pwdvalue)) {
			return Result.error("参数错误");
		}

		try {
			/*if(StringUtils.isEmpty(captcha) || !checkSessionLoginCode(request, captcha)) {
				return Result.error("验证码错误");
			}*/
			
			UserConfigVo userConfigVo = userConfigAo.queryByUserName(username);
			if (userConfigVo == null) {
				return Result.error("用户不存在");
			}

			if (!MD5.md5Encode(pwdvalue).equals(userConfigVo.getPassword())) {
				return Result.error("密码错误");
			}

			super.setSessionUser(request, userConfigVo);

			//更新登录记录
			userConfigVo.setLastLoginTime(System.currentTimeMillis());
			userConfigVo.setLoginTimes(userConfigVo.getLoginTimes() == null ? 1 : userConfigVo.getLoginTimes() + 1);
			userConfigVo.setLastLoginIp(IpUtils.getIpAddr(request));
			userConfigAo.updateUserConfig(userConfigVo);
		} catch (Exception e) {
			logger.error("",e);
			return Result.error("账户验证失败");
		}

		return Result.ok();
	}
	
	/**
	 * 修改密码
	 * @param request
	 * @param pwdvalue
	 * @param newPassword
	 * @return
	 */
	@SysLog(option="修改",value="修改密码")
	@RequestMapping(value = SystemUrlUtil.MODIFY_CIPHER)
	@ResponseBody
	public Result modifyPassword(HttpServletRequest request,String pwdvalue,String newPassword) {
		
		if (StringUtils.isEmpty(pwdvalue) || StringUtils.isEmpty(newPassword)) {
			return Result.error("参数错误");
		}
		
		UserConfigVo user = super.getSessionUser(request);
		
		UserConfigVo userConfigVo = userConfigAo.queryById(user.getId());
		
		if (userConfigVo == null) {
			return Result.error("用户不存在");
		}

		if (!MD5.md5Encode(pwdvalue).equals(userConfigVo.getPassword())) {
			return Result.error("原密码错误");
		}
		
		userConfigVo.setPassword(MD5.md5Encode(newPassword));
		userConfigAo.updateUserConfig(userConfigVo);
		
		return Result.ok();
	}

	/**
	 * 退出
	 */
	@SysLog(option="注销",value="退出系统")
	@GetMapping(value = SystemUrlUtil.DO_LOGOUT)
	public void logout(HttpServletRequest request, HttpServletResponse response) {

		super.removeSessionUser(request);

		super.sendRedirect(response, "login.htm");
	}

}
